package comWorld.msg;

import java.util.ArrayList;
import java.util.List;

import com.gjs.tools.JDBC.JDBCTools;

import dataManage.tools.Sequence;

public class MessageManage {
	public static int getNextMsgId() {
		return Sequence.queryNextVal("msg_id_sq");
	}
	
	public static boolean addMsg(Message msg) {
		String sql = "INSERT INTO messages VALUES(?,?,?,?,?,?,?,?,?)";
		return JDBCTools.insert(sql, msg.getUserId(), msg.getReceiverId(), msg.getSenderId(), 
				msg.getMsgId(), msg.getContent(), msg.getSendTime(), msg.getIsNew(), msg.getOtherId(), msg.getType()) > 0;
	}
	
	public static boolean deleteAllMsgs(int userId, int otherId) {
		String sql = "DELETE FROM messages WHERE user_id = ?";
		if (otherId != 0) {
			sql += " AND other_id = ?";
			return JDBCTools.update(sql, userId, otherId) >= 0;
		}
		return JDBCTools.update(sql, userId) >= 0;
	}
	
	public static boolean deleteMsg(int userId, int msgId) {
//		System.out.println(userId + "," + msgId);
		String sql = "DELETE FROM messages WHERE user_id = ? AND msg_id = ?";
		return JDBCTools.update(sql, userId, msgId) > 0;
	}
	
	public static List<Message> getMsgs(int userId, String type, Object value) {
		String sql = "SELECT msg.user_id userId, ui.user_name userName, ui.head_image userHeadImage, receiver_id receiverId, sender_id senderId, msg_id msgId,"
				+ " msg.content, sendTime, is_new isNew, other_id otherId, uit.user_name otherName, uit.head_image otherHeadImage "
				+ "FROM messages msg, user_info ui, user_info uit WHERE msg.user_id = ? AND msg.user_id = ui.id AND msg.other_id = uit.id";
		if (type.equals("box")) {
			List<Message> msgs = JDBCTools.getObjects(Message.class, sql + " ORDER BY msg.other_id", userId);
			if (!Message.TYPE_ONE.equals(value)) {
				sql += " AND type = ? ORDER BY msg.other_id";
				msgs = JDBCTools.getObjects(Message.class, sql, userId, value);
			}
			
			List<Message> realMsgs = new ArrayList<Message>();
			int otherId = 0;
			String lastSendTime = "";
			Message lastMsg = null;
			int count = 0;
			for (Message msg : msgs) {
				if (otherId == msg.getOtherId()) {
					if (lastSendTime.compareTo(msg.getSendTime()) < 0) {
						lastSendTime = msg.getSendTime();
						lastMsg = msg;
					}
					count++;
				} else {
					if (count != 0) {
						lastMsg.setTotalMsgs(count);
						realMsgs.add(lastMsg);
					}
					count = 0;
					count++;
					lastMsg = msg;
					otherId = msg.getOtherId();
					lastSendTime = msg.getSendTime();
				}
			}
			if (lastMsg != null) {
				lastMsg.setTotalMsgs(count);
				realMsgs.add(lastMsg);
			}
			
			return realMsgs;
		}
		
		else if (type.equals("msgs")) {
			sql += " AND msg.other_id = ? ORDER BY sendTime DESC";
			return JDBCTools.getObjects(Message.class, sql, userId, value);
		}
		
		return null;
	}
}
